/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { Component } from "react";
import { connect } from "dva";
import { Table, Form, DatePicker, Select, Spin, Button, Row, Col } from "antd";
import moment from "moment/moment";
import { debounce } from "lodash";
import StandardTable from "@/components/StandardTable";
import DownloadBar from "@/components/DownloadBar";
import styles from "./style.less";

const { RangePicker } = DatePicker;
const FormItem=Form.Item;
const { Option } = Select;
const dateFormat = "YYYY-MM-DD";
@connect(({ loading,dispat,report,list }) => ({
  dispat,
  report,
  list,
  stationing: loading.effects["area/subList"],
  getFeeApply: loading.effects["dispat/feeApply"],
  getRecord: loading.effects["dispat/getRecord"],
  getRecordDetailed: loading.effects["dispat/getRecordDetailed"],
}))
@Form.create()
class ServiceRecord extends Component {
  constructor(props){
      super(props);
      this.state = {
        detailed:true,
        feeDetail_start:moment().startOf("day").subtract(7, "days"),
        feeDetail_end:moment().endOf("day").subtract(1, "days"),
        feeDetail_inn_name:"",
        cmId:"all",
      };
      
  }
  componentDidMount() {
    const { dispatch, } = this.props;
    this.getFormValues(values => {
      if (!values.cm_id) {
        values.cm_id = "all" ;
      }
      dispatch({
        type: `dispat/getRecord`,
        payload: {
          ...values,
          cm_id: values.cm_id
        }
      });
    });
  }

  getFormValues = then => {
    const { form } = this.props;
    const {cm_id} = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        cm_id:cm_id,
      };
      const { date } = fieldsValue;
      if (date) {
        values.date = date.map(d => moment(d).format("YYYY-MM-DD"));
        const [start, end] = values.date;
        values.start_date = start;
        values.end_date = end;
        delete values.date;
      }
      this.setState({
        formValues: values
      });
      then(values);
    });
  };

  handleStandardTableChange = debounce(pagination => {
    const { dispatch, } = this.props;
    const { formValues } = this.state;
    const params = {
      page: pagination.current,
      ...formValues
    };
    dispatch({
      type: `dispat/getRecord`,
      payload: params
    });
  }, 500, {
    leading: true,
    trailing: false
  });

  handleSearchForthe = debounce(e => {
    e.preventDefault();
    const { dispatch, } = this.props;
    this.getFormValues(values => {
      if (!values.cm_id) {
        values.cm_id = "all" ;
      }
      dispatch({
        type: `dispat/getRecord`,
        payload: {
          ...values,
          cm_id: values.cm_id
        }
      });
      this.setState({
        cm_id: values.cm_id,
      })
    });
  }, 500, {
    leading: true,
    trailing: false
  });

  downloadData = () => {
    const {cm_id}=this.state;
    const { form: { getFieldsValue } } = this.props;
    const {
      date
    } = getFieldsValue();
    const cm_ids = cm_id || "all";
    const oData = {
      cm_id:cm_ids,
      start_date: moment(date[0]).format(dateFormat),
      end_date: moment(date[1]).format(dateFormat)
    };
    return { ...oData };
  };

  disabledDate = (current) => {
    // Can not select days before today and today
    return current && current > moment().endOf("day").subtract(1, "days");
  };

  dataClick = data => {
    const setFieldsValueDate = {
      startDate: moment()
        .startOf("day")
        .subtract(data, "days"),
      endDate: moment().endOf("day").subtract(1, "days")
    };
    this.props.form.setFieldsValue({
      "date": [setFieldsValueDate.startDate, setFieldsValueDate.endDate]
    });
  };

  // 驿站下拉
  getStationList = (visible) => {
    if (!visible) return;
    const { dispatch } = this.props;
    dispatch({
      type: "report/getYzList",
      payload: ""
    });
  };

  onFilterOperator = (inputValue, options) => {
    const { children, value } = options.props;
    if (children.indexOf(inputValue) >= 0) return true;
  };

  selectCurrency = (e,labe) => {
    this.setState({
      cm_id:labe.key,
      cmId:labe.props.value,
    })
  }

  changeSelect = (value) => {
      if(!value){
        this.setState({
          cm_id:"all",
          cmId:"all",
        })
      }
  }

  // 品牌下拉
  getOperatorList = (visible) => {
    if (!visible) return;
    const { dispatch } = this.props;
    dispatch({
      type: "list/getBrandsList",
      payload: {
        shop_id:""
      },
    });
  };

  // 明细
  clickTime = (value) => {
    this.setState({
      detailed:false,
      feeDetail_inn_name:value.inn_name,
    })
    const { dispatch, } = this.props;
    this.getFormValues(values => {
      if (!values.cm_id) {
        values.cm_id = "all" ;
      }
      dispatch({
        type: `dispat/getRecordDetailed`,
        payload: {
          ...values,
          cm_id: value.cm_id
        }
      });
      this.setState({
        feeDetail_start:values.start_date,
        feeDetail_end:values.end_date,
      })
    });
  }

  // 关闭明细
  cancel = () => {
    this.setState({
      detailed:true,
    })
  }

  render() {
    const {detailed,feeDetail_start,feeDetail_end,feeDetail_inn_name,cm_id,cmId}=this.state;
    const {
        dispat:{recordList,summery,recordListDetailed,summeryDetailed},
        form,
        stationing,
        report,
        getRecord,
        getRecordDetailed,
      }=this.props;
    const { getFieldDecorator } = form;
    const yzList = (report && report.yzList) || [];
    const {total_waybill,total_fee}=summery;
    const {total_waybill:total_waybill_Detailed,total_fee:total_fee_Detailed}=summeryDetailed;
    const {list:feeDetailList,pagination:feeDetailPagination}=recordListDetailed;
    const {total}=feeDetailPagination;
    const columns = [
      {
        title: '驿站名称',
        dataIndex: 'inn_name',
        key: 'inn_name',
      },
      {
        title: `入库数${total_waybill||0}条`,
        dataIndex: 'total_waybill',
        key: 'total_waybill',
      },
      {
        title: `入库服务费${total_fee||0}元`,
        dataIndex: 'total_fee',
        key: 'total_fee',
        render: (current, currentData) => {
          return (
            <a onClick={() => this.clickTime(currentData)}>
              {current}
            </a>
          );
        }
      },
    ];

    const columnsDetailed = [
      {
        title: '日期',
        dataIndex: 'date',
        key: 'date',
      },
      {
        title: `入库数${total_waybill_Detailed||0}条`,
        dataIndex: 'total_waybill',
        key: 'total_waybill',
      },
      {
        title: `入库服务费${total_fee_Detailed||0}元`,
        dataIndex: 'total_fee',
        key: 'total_fee',
      },
    ];

    const defaultSelectDate = {
      startDate: moment()
        .startOf("day")
        .subtract(7, "days"),
      endDate: moment().endOf("day").subtract(1, "days")
    };
    return (
      <div style={{ paddingTop: 10 }}>
        {
          detailed ? (
            <div>
                <Form
                  onSubmit={this.handleSearchForthe}
                  className={styles["search-form"]}
                  layout="inline"
                >
                  <FormItem>
                    <a className={styles.select_date} onClick={() => this.dataClick(1)}>
                      昨日
                    </a>
                    <a className={styles.select_date} onClick={() => this.dataClick(7)}>
                      近7日
                    </a>
                    <a className={styles.select_date} onClick={() => this.dataClick(30)}>
                      近30日
                    </a>
                  </FormItem>
                  <FormItem className={styles.data}>
                    {getFieldDecorator("date", {
                      initialValue: [moment(feeDetail_start), moment(feeDetail_end)]
                    })(
                      <RangePicker
                        style={{ width: "280px" }}
                        placeholder={["开始日期", "结束日期"]}
                        disabledDate={this.disabledDate}
                        />)}
                  </FormItem>
                  <FormItem className={styles.data}>
                    {getFieldDecorator("cm_id", {
                      initialValue: cmId,
                    })(
                      <Select
                        onDropdownVisibleChange={this.getStationList}
                        filterOption={this.onFilterOperator}
                        placeholder="全部驿站"
                        showSearch
                        allowClear
                        style={{ width: "150px" }}
                        onSelect={this.selectCurrency}
                        onChange={this.changeSelect}
                      >
                        {stationing ? (
                          <Option disabled value="loading">
                            <Spin />
                          </Option>
                        ) : (
                          <Option key="all" value="all">
                            全部驿站
                          </Option>
                        )}
                        {yzList.map(({ cm_id, company_name, id }) => (
                          <Option key={`${cm_id}`} value={id}>
                            {company_name}
                          </Option>
                        ))}
                      </Select>
                    )}
                  </FormItem>
                  
                  <FormItem>
                    <span className={styles.submitButtons}>
                      <Button type="primary" htmlType="submit" key="search" loading={getRecord} icon="search">
                        查询
                      </Button>
                    </span>
                    <div
                      style={{
                        paddingBottom: "24px",
                        marginLeft: "16px",
                        display: "inline-block"
                      }}
                    >
                      <DownloadBar
                        href={"/Api/YZ/Fund/export"}
                        query={this.downloadData}
                      >
                        <Button type="primary" icon="download">
                          下载
                        </Button>
                      </DownloadBar>
                    </div>
                  </FormItem>
                </Form>
                <StandardTable
                  rowKey="cm_id"
                  loading={getRecord}
                  data={recordList}
                  columns={columns}
                  onChange={this.handleStandardTableChange}
                />
            </div>
          ) : (
            <div>
                <h2>入库服务费明细</h2>
                <FormItem>
                  <Row>
                    <Col xs={24} sm={24} md={24} lg={12} xl={8}>
                      <span>
                        选定日期：
                        {feeDetail_start}到{feeDetail_end}
                      </span>
                    </Col>
                    <Col xs={24} sm={24} md={24} lg={12} xl={6}>
                      <span>
                        所选驿站：
                        {feeDetail_inn_name}
                      </span>
                    </Col>
                    <Col xs={24} sm={24} md={24} lg={24} xl={3}>
                      <Button
                        type="primary"
                        onClick={this.cancel}
                      >
                        返回
                      </Button>
                    </Col>
                  </Row>
                </FormItem>
                
                <Table
                  rowKey="date"
                  loading={getRecordDetailed}
                  dataSource={feeDetailList}
                  columns={columnsDetailed}
                  onChange={this.handleStandardTableChange}
                  pagination={{
                    defaultPageSize:total * 1,
                    hideOnSinglePage:true
                  }}
                />
            </div>
          )
        }
      </div>
    );
  }
}

export default ServiceRecord;
